package Dao;


import pojo.Car;

import java.io.*;
import java.util.ArrayList;

/**
 * 车辆初始化
 */
public class CarDao {
    private static ArrayList<Car> cars=new ArrayList<>();
    private static File file=new File(FileLocation.file+"\\Car.txt");
    static {
        Car car1=new Car(1,"郎逸","自动1.6L","大众(2)","舒适型(2)",72.0,true,true,"鲁B6666",150000,"黑色");
        Car car2=new Car(2,"途观","自动1.8T","大众(2)","SUV(3)",200.0,true,true,"鲁B6666",170000,"白色");
        Car car3=new Car(3,"A4L","自动2.0T","奥迪(3)","精英型(4)",359.0,true,true,"鲁B6666",240000,"红色色");
        Car car4=new Car(4,"308","手动1.6L","标致(1)","紧凑型(1)",56.0,true,true,"鲁B6666",800000,"蓝色");
        Car car5=new Car(5,"308S","自动1.2T","标致(1)","舒适型(2)",70.0,true,true,"鲁B6666",640000,"白色");
        Car car6=new Car(6,"高尔夫","自动1.4T","大众(2)","紧凑型(1)",69.0,true,true,"鲁B6666",450000,"绿色");
        Car car7=new Car(7,"320Li","自动2.0T","宝马(5)","精英型(4)",500.0,true,true,"鲁B6666",560000,"黑色");
        Car car8=new Car(8,"B200","自动1.6T","奔驰(4)","精英型(4)",300.0,true,true,"鲁B6666",890000,"黑色");
        cars.add(car1);
        cars.add(car2);
        cars.add(car3);
        cars.add(car4);
        cars.add(car5);
        cars.add(car6);
        cars.add(car7);
        cars.add(car8);
    }

    /**
     * 反序列化对象
     * @return
     */
    public static ArrayList<Car> getCars() {
        FileInputStream input=null;
        ObjectInputStream oInput = null;
        try {
            if (!file.exists()){
                file.createNewFile();
            }
            input = new FileInputStream(file);
            oInput = new ObjectInputStream(input);
            cars= (ArrayList<Car>) oInput.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                oInput.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return cars;
    }

    /**
     * 序列化对象
     */
    public static void setCars() {
        FileOutputStream input=null;
        ObjectOutput oOut=null;
        try {
            if (!file.exists()){
                file.createNewFile();
            }
            input = new FileOutputStream(file);
            oOut = new ObjectOutputStream(input);
            oOut.writeObject(cars);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oOut.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
